package com.example.ymm.modules1.service.impl.hl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmb.xft.open.api.Sm4Util;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.UserLogin;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.dkn.DknTrialItem;
import com.example.ymm.modules1.entity.hl.dkn.DknTrialLog;
import com.example.ymm.modules1.entity.hl.yw.YwApprove;
import com.example.ymm.modules1.entity.hl.yw.YwMoneyAffirmLog;
import com.example.ymm.modules1.entity.hl.yw.YwUser;
import com.example.ymm.modules1.entity.my.user.DbApprovalLog;
import com.example.ymm.modules1.entity.my.user.DbComment;
import com.example.ymm.modules1.entity.my.user.DbError;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.mapper.hl.YwApproveMapper;
import com.example.ymm.modules1.query.hl.DknTrialItemQueryCriteria;
import com.example.ymm.modules1.query.hl.YwApproveQueryCriteria;
import com.example.ymm.modules1.query.hl.YwMoneyAffirmLogQueryCriteria;
import com.example.ymm.modules1.service.dto.heng.*;
import com.example.ymm.modules1.service.dto.ms.MsMoneyAffirmDto;
import com.example.ymm.modules1.service.hl.*;
import com.example.ymm.modules1.service.ms.DEmployeeService;
import com.example.ymm.modules1.service.user.DbApprovalLogService;
import com.example.ymm.modules1.service.user.DbCommentService;
import com.example.ymm.modules1.service.user.DbErrorService;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.modules1.service.xft.XftService;
import com.example.ymm.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

@Service
// @Transactional
@Slf4j
@DS("slave2")
public class YwApproveServiceImpl extends BaseServiceImpl<YwApproveMapper, YwApprove> implements YwApproveService {

    @Autowired
    YwMoneyAffirmLogService ywMoneyAffirmLogService;

    @Autowired
    XftService xftService;

    @Autowired
    DEmployeeService dEmployeeService;

    @Autowired
    YwUserService ywUserService;

    @Autowired
    DbErrorService dbErrorService;

    @Autowired
    DbCommentService dbCommentService;

    @Value("${xft.pubKey}")
    String pubKey;

    @Value("${spring.profiles.active}")
    private String PD_MATCH;

    @Autowired
    DbUserService dbUserService;

    @Autowired
    DknTrialItemService dknTrialItemService;

    @Autowired
    DknTrialLogService dknTrialLogService;

    @Autowired
    DbApprovalLogService dbApprovalLogService;

    //流程试算响应结果
    Map<String,ApproveRespond> respondMap = new HashMap<>();

    @Override
    public TableList<YwApprove> list(YwApproveQueryCriteria criteria, YmPageDto pageDto) {
        IPage<YwApprove> page = new Page<YwApprove>(pageDto.getPage(), pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(YwApprove.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<YwApprove> tableList = new TableList(page);
        List<YwApprove> list = tableList.getList();

        return tableList;
    }

    @Override
    public TableList<YwApprove> xftList(YwApproveQueryCriteria criteria, YmPageDto ymPage) {
        String userRole = getUserRole();
        if (!"manage".equals(userRole)) {
            String userName = getUserName();
            YwUser user = ywUserService.getMemberId(userName);
            if (UtilValidate.isNotEmpty(user)) {
                criteria.setMemberId(user.getMemberId());
            }
        }
        return xftService.approvalDataList(criteria, ymPage);
    }

    public List<YwApprove> queryAll(YwApproveQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(YwApprove.class, criteria);
        predicate.orderByDesc("create_time");
        List<YwApprove> result = baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public String getUserNo(String userName) {
        String userNo = "";
        // 动态切换数据源
        DynamicDataSourceContextHolder.push("slave");
        userNo = dEmployeeService.getTidByName(userName);
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("slave2");
        return userNo;
    }

    @Override
    public void approveCreateBefore(YwApproveCreateDto dto) {
        // String userName = getUserName();
        ApproveRespond respond = new ApproveRespond();
        respond.setThreadId(dto.getThreadId());
        respond.setSubTime(dto.getSubTime());
        // String userNo = getUserNo(dto.getUserName());
        YwUser ywUser = ywUserService.getMemberId(dto.getUserName());
        dto.setUserNo(ywUser.getUserNo());
        dto.setMemberId(ywUser.getMemberId());
        List<MsMoneyAffirmDto> list = dto.getList();
//        List<String> msg = new ArrayList<>();

        long start_time = System.currentTimeMillis();

        DknTrialLog trialLog=new DknTrialLog();
        trialLog.setUserId(ywUser.getUserNo());
        trialLog.setUserName(ywUser.getUserName());
        for (int i = 0; i < list.size(); i++) {
            MsMoneyAffirmDto msMoneyAffirmDto = list.get(i);

//            if (UtilValidate.isEmpty(msMoneyAffirmDto.getReceiverUserPrice0())) {
//                msg.add("第" + (i + 1) + "条数据的接单人抽成金额为空！");
//            }
//            int receiverUserPriceCompare = msMoneyAffirmDto.getReceiverUserRate0().compareTo(BigDecimal.ZERO);
//            if (receiverUserPriceCompare <= 0) {
//                msg.add("第" + (i + 1) + "条数据的接单人抽成比例为空！");
//                // return msg;
//            } else {
//                if (UtilValidate.isEmpty(msMoneyAffirmDto.getReceiverUserName0())) {
//                    msg.add("第" + (i + 1) + "接单人有抽成金额但是接单人却为空！");
//                }
//            }

        }

        List<YwMoneyAffirmLog> logs = new ArrayList<>();
        Long maxNum = ywMoneyAffirmLogService.getMaxNum();

        for (MsMoneyAffirmDto item : list) {
            YwMoneyAffirmLog ywMoneyAffirmLog = new YwMoneyAffirmLog();
            ywMoneyAffirmLog.setApproveNo(dto.getApproveNo());
            ywMoneyAffirmLogService.adapterAffirmDtoToAffirmLog(item, ywMoneyAffirmLog);
            maxNum = maxNum + 1;
            ywMoneyAffirmLog.setLineId(maxNum);
            logs.add(ywMoneyAffirmLog);
        }

        // String jsonString = JSONObject.toJSONString(dto);
        XftApproveCreateDto dto1 = new XftApproveCreateDto();
        dto1.setApproveNo(dto.getApproveNo());
        dto1.setUserName(dto.getUserName());
        dto1.setUserNo(dto.getUserNo());
        dto1.setMemberId(dto.getMemberId());
        dto1.setList(logs);
        System.out.println("---流程试算开始:");
        System.out.println("--createApproveNo::::");
        System.out.println(dto1.getApproveNo());
        JSONObject trialData = xftService.approveTrialFn(dto1);
        JSONArray jsonArray = trialData.getJSONArray("startNodeList");
        if (UtilValidate.isNotEmpty(jsonArray)) {
            JSONObject jsonObject = jsonArray.getJSONObject(0).getJSONArray("approverUserList").getJSONObject(0);
            if (UtilValidate.isEmpty(jsonObject.getString("userName"))) {
                jsonObject.put("userName", dto.getUserName());
            }
        }
         String trialId = trialData.getString("trialId");//拿到了试算结果id
        dto1.setTrialData(trialData);
        dto1.setTrialId(trialId);

        // return null;

        DknTrialLog dknTrialLog=new DknTrialLog();
        dknTrialLog.setId(dto.getThreadId());
        dknTrialLog.setTrialId(trialId);
        dknTrialLog.setParameter(JSONObject.toJSONString(dto1));
        dknTrialLog.setBody(trialData.toJSONString());
        dknTrialLog.setStatus(1);
        dknTrialLog.setIsSubmit(1);
        dknTrialLogService.updateById(dknTrialLog);

        respond.setDto(dto1);
        long end_time = System.currentTimeMillis();
        float duration = (end_time - start_time)/60f / 1000f;
        respond.setTimeLength(duration);
//        System.out.println("--试算耗时:" + duration);
//        System.out.println("---流程试算结束:");
//        System.out.println(respond);
        // approveCreateAfter(dto1);

//        respondMap.put(respond.getThreadId(), respond);
        approveSubmit(dto1);
    }


    @Override
    public ApproveRespond getTimingMap(String threadId) {
        return respondMap.get(threadId);
    }

    @Override
    public XftApproveCreateDto approveCreateAfter(XftApproveCreateDto submitDto) {

        JSONObject jsonObject = xftService.approveCreate(submitDto);
        // submitDto.setApproveNo(submitDto.getApproveNo());
        // submitDto.setUserNo(submitDto.getUserNo());
        // submitDto.setUserName(submitDto.getUserName());
        submitDto.setTrialData(jsonObject);
        return submitDto;
    }

    @Override
    public void approveDelete(String approveNo) {

    }

    @Override
    public void approveSubmit(XftApproveCreateDto submitDto) {
        // String userName = getUserName();
        // String userNo = getUserNo(userName);
//        if (UtilValidate.isEmpty(submitDto.getApproveNo())) {
//            throw new YmException("非法参数!");
//        }
//        if (UtilValidate.isEmpty(submitDto.getTrialData())) {
//            throw new YmException("非法参数!");
//        }

        approveCreateAfter(submitDto);
        JSONObject trialData = submitDto.getTrialData();

        YwApprove approve = new YwApprove();
        approve.setApproveNo(submitDto.getApproveNo());
        approve.setMemberId(submitDto.getMemberId());
        approve.setUserNo(submitDto.getUserNo());
         approve.setUserName(submitDto.getUserName());
        approve.setBusKey(trialData.getString("busKey"));
        approve.setTrialId(submitDto.getTrialId());

//        if (UtilValidate.isEmpty(approve.getBusKey())) {
//            throw new YmException("参数缺失!");
//        }
//        YwApproveQueryCriteria criteria = new YwApproveQueryCriteria();
//        criteria.setBusKey(approve.getBusKey());
//        List<YwApprove> ywApproves = queryAll(criteria);
//        if(UtilValidate.isNotEmpty(ywApproves)) {
//            throw new YmException("该抽成已提交过不可重复提交!");
//        }
        approve.setState(trialData.getString("procStatus"));
        approve.setBody(trialData.toJSONString());

        saveOrUpdate(approve);
        ywMoneyAffirmLogService.saveOrUpdateBatch(submitDto.getList());

        // 数据采集
        // importJsonData(approve.getBusKey());

    }

    @Override
    public void approveCancel(String approveId) {

        YwApprove approve = getById(approveId);
        YwUser ywUser = ywUserService.getMemberId(approve.getUserName());
        JSONObject jsonObject = xftService.approveCancel(ywUser.getMemberId(), approve.getBusKey());
        if (UtilValidate.isNotEmpty(jsonObject)) {
            approve.setBody(jsonObject.toJSONString());
            approve.setBusKey(jsonObject.getString("busKey"));
            approve.setState(jsonObject.getString("procStatus"));
            approve.setIsNoShow(1);
            approve.setStateName("已撤销");
            saveOrUpdate(approve);

            dknTrialLogService.removeByTrialId(approve.getTrialId());
            // removeById(approveId);
            ywMoneyAffirmLogService.removeByApproveNo(approve.getApproveNo());
        }

    }


    @Override
    public void approveAbolish(String approveId) {
        YwApprove approve = getById(approveId);
        approve.setStateName("已作废");
        saveOrUpdate(approve);
        YwMoneyAffirmLogQueryCriteria criteria=new YwMoneyAffirmLogQueryCriteria();
        criteria.setApproveNo(approve.getApproveNo());
        List<YwMoneyAffirmLog> logs = ywMoneyAffirmLogService.queryAll(criteria);
        for(YwMoneyAffirmLog alog:logs){
            alog.setOrderNo(alog.getOrderNo()+"已作废");
            ywMoneyAffirmLogService.saveOrUpdate(alog);

        }
    }

    @Override
    public JSONArray importJsonDataPeiSong(YwApprove approve,String approvalName,DbApprovalLog approvalLog) {
        JSONArray array = null;
        List<ImportXftDataDto> list=new ArrayList<>();
        String footList = approve.getFootList();
        JSONObject jsonObject = JSONObject.parseObject(footList);
        JSONArray jsonArray = jsonObject.getJSONArray("group_user_list");
        //薪资所属期 归到上个月
        Date lastMonthBegin = DateKit.getLastMonthBegin();
        String addTime = DateKit.dateFormat(lastMonthBegin, "yyyyMM");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);
            JSONArray jsonArray1 = json.getJSONArray("childen");
            for (int j = 0; j < jsonArray1.size(); j++) {
                JSONObject json1 = jsonArray1.getJSONObject(j);
                if(json1.containsKey("total")){
                    String userName=json1.getString("userName");
                    BigDecimal total = json1.getBigDecimal("total");
                    ImportXftDataDto dataDto=new ImportXftDataDto();
                    dataDto.setApproveNo(approve.getApproveNo());
                    dataDto.setApproveType(approvalName);
                    dataDto.setDeptName(approvalLog.getDeptName());
                    dataDto.setUserPrice(total);
                    dataDto.setUserName(userName);
//                    dataDto.setAddDate(addTime);
                    list.add(dataDto);
                }
            }
        }
        ImportJsonDataDto dto=new ImportJsonDataDto();
        dto.setApproveNo(approve.getApproveNo());
        dto.setApprove(approve);
        dto.setList(list);
        dto.setType("配送费审批");
        array= xftService.importJsonData(dto);

        return array;
    }


    /**
     * 抽成数据推送到数据采集表
     * @param approve
     * @param approvalName
     * @param approvalLog
     * @return
     */
    @Override
    public JSONArray importJsonYwChouCheng(YwApprove approve, String approvalName, DbApprovalLog approvalLog) {
        JSONArray array = null;
        List<ImportXftDataDto> list=new ArrayList<>();

        //薪资所属期 归到上个月
        Date lastMonthBegin = DateKit.getLastMonthBegin();
        String addTime = DateKit.dateFormat(lastMonthBegin, "yyyyMM");
        String userName=null;
        BigDecimal total = null;
        ImportXftDataDto dataDto=new ImportXftDataDto();
        dataDto.setApproveNo(approve.getApproveNo());
        dataDto.setApproveType(approvalName);
        dataDto.setDeptName(approvalLog.getDeptName());
        dataDto.setUserPrice(total);
        dataDto.setUserName(userName);

        list.add(dataDto);

        return array;
    }

    /**
     * 审批结束事件
     * 
     * @param params
     */
    public void approveEndEvent(JSONObject params) {

        try {

            // 数据签名验证开始（非必要过程）
            // String
            // pubKey="0436f8729f91602a18904a48cec2ddf94b720ee6bd05727e9cde5b4ad58a4a9997fee422334b76c0b20e017a65dd1e549d7ea83b1bba8a9b5cdf630f7a8959fdec";
            Map<String, Object> treeMap = new TreeMap<>();
            treeMap.put("eventId", params.get("eventId"));
            treeMap.put("prjCod", params.get("prjCod"));
            treeMap.put("eventTime", params.get("eventTime"));
            // eventCd为数据类型，不能用String接收，否则签名验证不通过
            treeMap.put("eventCd", Long.parseLong(String.valueOf(params.get("eventCd"))));
            String signature = String.valueOf(params.get("signature"));
            String dataSign = JSONObject.toJSONString(treeMap);
            boolean flag = SM2VerifyUtils.verify(pubKey, dataSign, signature);
            if (!flag) {
                throw new YmException("验签失败");
            }
            // 签名验证结束
            // 获取内容
            String eventRcdInf = String.valueOf(params.get("eventRcdInf"));
            // 解密
            String key = pubKey.substring(0, 32);
            eventRcdInf = Sm4Util.decryptEcb(key, eventRcdInf);
            System.out.println("---eventRcdInf");
            System.out.println(eventRcdInf);
            JSONObject event = JSONObject.parseObject(eventRcdInf);
            String busKey = event.getString("busKey");
            YwApproveQueryCriteria criteria = new YwApproveQueryCriteria();
            criteria.setBusKey(busKey);
            YwApprove approve = null;
            List<YwApprove> ywApproves = queryAll(criteria);
            if (UtilValidate.isNotEmpty(ywApproves)) {
                approve = ywApproves.get(0);
            }
            if(UtilValidate.isNotEmpty(approve)){
                String procStatus = event.getString("procStatus");
                approve.setState(procStatus);
//            saveOrUpdate(approve);
                // JSONArray jsonObject1 = importJsonData(busKey);
                // log.info("---数据采集推送结果:"+jsonObject1);
                if("PASSED".equals(procStatus)){
                    // 推送数据采集表
//                    JSONArray array = importJsonData(approve.getBusKey());
//                    if (UtilValidate.isNotEmpty(array)) {
//                        String errorMessage = array.getJSONObject(0).getString("errorMessage");
//                        if (UtilValidate.isNotEmpty(errorMessage)) {
//                            throw new YmException(errorMessage);
//                        }
//                    }
                    approve.setIsSync(1);
                }

                saveOrUpdate(approve);
            }else{
               EmailUtil.sendEmail("1055162826@qq.com","审批结束异常","busKey查询不到"+busKey);
            }


        } catch (Exception e) {
            if ("prod-new".equals(PD_MATCH)) {
                DbError error = new DbError();
                error.setMsg(e.getMessage());
                error.setRemark(params.toJSONString());
//                String userName = getUserName();
                error.setUserName("审批结束事件");
                dbErrorService.addError(error);
                log.error("审批结束事件异常：" + e.getMessage(), e);
            } else {
                e.printStackTrace();
            }
            throw new YmException(e.getMessage());
            //
            // e.printStackTrace();
        }
    }

    @Override
    public void syncTable() {
        YwApproveQueryCriteria criteria = new YwApproveQueryCriteria();
        criteria.setIsSync(0);
        criteria.setState("PASSED");
        List<YwApprove> ywApproves = queryAll(criteria);
        for (YwApprove ywApprove : ywApproves) {
            try {
//                JSONArray array = importJsonData(ywApprove.getBusKey());
//                if (UtilValidate.isNotEmpty(array)) {
//                    String errorMessage = array.getJSONObject(0).getString("errorMessage");
//                    if (UtilValidate.isNotEmpty(errorMessage)) {
//                        throw new YmException(errorMessage);
//                    }
//                }
                ywApprove.setIsSync(1);
                saveOrUpdate(ywApprove);
            } catch (Exception e) {
                if ("prod-new".equals(PD_MATCH)) {
                    DbError error = new DbError();
                    error.setMsg(e.getMessage());
                    error.setRemark(ywApprove.getApproveNo());
                    // String userName = getUserName();
                    // error.setUserName(userName);
                    dbErrorService.addError(error);
                    log.error("定时推送数据采集表异常：" + e.getMessage(), e);
                } else {
                    e.printStackTrace();
                }
            }
        }

    }


    @Override
    public YwApprove findByApproveNo(String approveNo) {
        YwApproveQueryCriteria criteria=new YwApproveQueryCriteria();
        criteria.setApproveNo(approveNo);
        List<YwApprove> ywApproves = queryAll(criteria);
        if(ywApproves.size()>0){
            return ywApproves.get(0);
        }
        return null;
    }



    /**
     * ----------------------以上是薪福通的审批 以下是自研系统的审批----------------
     */


    @Override
    public ApprovalCreateViewDto ywApprovalCreateView(String approvalName,String title) {

        return dbApprovalLogService.approvalCreateView(approvalName,title);
    }


    @Override
    public ApprovalCreateViewDto ywApprovalLogView(String approveNo) {
        YwApprove ywApprove = findByApproveNo(approveNo);
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        return dbApprovalLogService.approvalLogView(approveNo,"业务员提成审批");
    }

    @Override
    public ApproveRespond ywApprovalSubmit(YwApproveCreateDto dto) {

        String userName = getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }
        DbUser dbUser = dbUserService.findByUserName(userName);
        if(UtilValidate.isNotEmpty(dbUser)){
            dto.setUserId(dbUser.getUserId());
        }
        //           String userNo = dEmployeeService.getTidByName(userName);
//            dto.setUserNo(userNo);
        dto.setUserName(userName);

        List<MsMoneyAffirmDto> list = dto.getList();
        ApproveRespond respond = new ApproveRespond();
        List<String> msg = new ArrayList<>();
        if (UtilValidate.isEmpty(list)) {
            msg.add("请选择要提交的数据！");
        }
        List<String> orderIn = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            MsMoneyAffirmDto dto1 = list.get(i);
            orderIn.add(dto1.getOrderNo());
        }
        YwMoneyAffirmLogQueryCriteria c=new YwMoneyAffirmLogQueryCriteria();
        c.setOrderNoIn(orderIn);
        List<YwMoneyAffirmLog> ywMoneyAffirmLogs = ywMoneyAffirmLogService.queryAll(c);
        if(UtilValidate.isNotEmpty(ywMoneyAffirmLogs)) {
            msg.add("当前付款编号已提交过不可重复提交！");
        }

        if(UtilValidate.isNotEmpty(msg)) {
            respond.setErrorMsg(msg);
            return respond;
        }
        CreateOrderNo createOrderNo = new CreateOrderNo();
        String orderNum = createOrderNo.makeOrderNum("YW");


        List<YwMoneyAffirmLog> logs = new ArrayList<>();
        List<DknTrialItem> trialItems = new ArrayList<>();
        for (MsMoneyAffirmDto item : list) {
            DknTrialItem dknTrialItem = new DknTrialItem();
//            dknTrialItem.setPId(dknTrialLog.getId());
            dknTrialItem.setOrderNo(item.getOrderNo());
            trialItems.add(dknTrialItem);

            YwMoneyAffirmLog ywMoneyAffirmLog = new YwMoneyAffirmLog();
            ywMoneyAffirmLog.setApproveNo(orderNum);
            ywMoneyAffirmLogService.adapterAffirmDtoToAffirmLog(item, ywMoneyAffirmLog);
            logs.add(ywMoneyAffirmLog);
        }


        //设置标题
        Date lastMonthBegin = DateKit.getLastMonthBegin();
        String title = DateKit.dateFormat(lastMonthBegin, "yyyy-MM");
        dto.setTitle(title+"提成");

        dto.setApproveNo(orderNum);
        respond.setApproveNo(orderNum);
        YwApprove approve = new YwApprove();
        approve.setApproveNo(orderNum);
        approve.setUserNo(dbUser.getUserId());
        approve.setUserName(dbUser.getUserName());
        approve.setType(1);
        approve.setApprovalName("业务员提成审批");
        saveOrUpdate(approve);


        ywMoneyAffirmLogService.saveOrUpdateBatch(logs);
        dbApprovalLogService.approvalSubmit(orderNum,"业务员提成审批",dto);


        return respond;
    }


    @Override
    public ApproveRespond ywApprovalFileSubmit(YwApproveCreateK3Dto dto) {
        String userName = getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }
        DbUser dbUser = dbUserService.findByUserName(userName);
        if(UtilValidate.isNotEmpty(dbUser)){
            dto.setUserId(dbUser.getUserId());
        }
        //           String userNo = dEmployeeService.getTidByName(userName);
//            dto.setUserNo(userNo);
        dto.setUserName(userName);
        MultipartFile file = dto.getFile();
        if(file.getSize()==0){
            throw new YmException("请上传附件！");
        }
        System.out.println(file.getOriginalFilename());
        ApproveRespond respond = new ApproveRespond();

        CreateOrderNo createOrderNo = new CreateOrderNo();
        String orderNum = createOrderNo.makeOrderNum("YW");
        YwApprove approve = new YwApprove();
        approve.setApproveNo(orderNum);
        approve.setUserNo(dbUser.getUserId());
        approve.setUserName(dbUser.getUserName());
        approve.setType(1);
        approve.setApprovalName("业务员提成审批");
        saveOrUpdate(approve);

        respond.setApproveNo(orderNum);

        Date lastMonthBegin = DateKit.getLastMonthBegin();
        String lastMonth = DateKit.dateFormat(lastMonthBegin, "yyyy-MM");
        String title="k3_"+lastMonth+"月回款明细";
        dto.setTitle(title);

        dbApprovalLogService.approvalSubmit(orderNum,"业务员提成审批",dto);
        return respond;
    }

    @Override
    public void ywApprovalPass(YwApprovaPassDto dto) {
        YwApprove ywApprove = findByApproveNo(dto.getApproveNo());
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        dbApprovalLogService.approvalPass(dto,"业务员提成审批");
    }

    @Override
    public void ywApprovalCancel(String approveNo) {
        YwApprove ywApprove = findByApproveNo(approveNo);
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        dknTrialLogService.removeByApproveNo(approveNo);
        // removeById(approveId);
        ywMoneyAffirmLogService.removeByApproveNo(approveNo);
        dbApprovalLogService.approvalCancel(approveNo,"业务员提成审批");
    }

    @Override
    public void ywApprovalRemove(String approveNo) {
        YwApprove ywApprove = findByApproveNo(approveNo);
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        DbApprovalLog approveNo1 = dbApprovalLogService.getApproveNo(approveNo);
        approveNo1.setStatus(0);
        dbApprovalLogService.saveOrUpdate(approveNo1);
        dknTrialLogService.removeByApproveNo(approveNo);
        // removeById(approveId);
        ywMoneyAffirmLogService.removeByApproveNo(approveNo);
    }

    @Override
    public void ywApprovalBack(YwApprovaPassDto dto) {
        YwApprove ywApprove = findByApproveNo(dto.getApproveNo());
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        dbApprovalLogService.approvalBack(dto,"业务员提成审批");
    }


    @Override
    public void addYwComment(YwApprovaPassDto dto) {

        DbApprovalLog approveNo = dbApprovalLogService.getApproveNo(dto.getApproveNo());
        if(UtilValidate.isEmpty(approveNo)){
            throw new YmException("参数有误！");
        }
        UserLogin userLogin = getUserLogin();
        DbComment dbComment = new DbComment();
        dbComment.setDataId(approveNo.getApprovalLogId());
        dbComment.setComment(dto.getComment());
        dbComment.setUserId(userLogin.getId());
        dbComment.setUserName(userLogin.getUserName());
        dbComment.setNote(approveNo.getPageName());
        dbCommentService.saveOrUpdate(dbComment);
    }


    /**
     * 配送费-------开始--------

     * @return
     */



    @Transactional
    public ApproveRespond ywPostageSubmit(YwPostageCreateDto dto) {
        String approvalName="配送费审批";
        String userName = getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }
        DbUser dbUser = dbUserService.findByUserName(userName);

        List<JSONObject> list = dto.getTableList();
        ApproveRespond respond = new ApproveRespond();
        List<String> msg = new ArrayList<>();
        if (UtilValidate.isEmpty(list)) {
            msg.add("请选择要提交的数据！");
        }
        List<String> orderIn = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = list.get(i);
            orderIn.add(jsonObject.getString("orderNo"));
        }

        DknTrialItemQueryCriteria c2=new DknTrialItemQueryCriteria();
        c2.setOrderNoIn(orderIn);
        c2.setApprovalName(approvalName);
        List<DknTrialItem> dknTrialItems = dknTrialItemService.queryAll(c2);
        if(UtilValidate.isNotEmpty(dknTrialItems)) {
            msg.add("当前付款编号已提交过不可重复提交！");
        }
        if(UtilValidate.isNotEmpty(msg)) {
            respond.setErrorMsg(msg);
            return respond;
        }
        CreateOrderNo createOrderNo = new CreateOrderNo();
        String orderNum = createOrderNo.makeOrderNum("PSF");

        List<DknTrialItem> logs = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject item = list.get(i);
            DknTrialItem dknTrialItem = new DknTrialItem();
            dknTrialItem.setApproveNo(orderNum);
            dknTrialItem.setJsonStr(item.toString());
            dknTrialItem.setUserId(dbUser.getUserId());
            dknTrialItem.setUserName(dbUser.getUserName());
            dknTrialItem.setOrderNo(item.getString("ziTid"));
            dknTrialItem.setState("提交");
            dknTrialItem.setSort(i);
            dknTrialItem.setApprovalName(approvalName);

            logs.add(dknTrialItem);
        }

        //设置标题
        Date lastMonthBegin = DateKit.getLastMonthBegin();
        String title = DateKit.dateFormat(lastMonthBegin, "yyyy-MM");
        dto.setTitle(title+"费用");

        dto.setApproveNo(orderNum);
        respond.setApproveNo(orderNum);
        YwApprove approve = new YwApprove();
        approve.setApproveNo(orderNum);
        approve.setUserNo(dbUser.getUserId());
        approve.setUserName(dbUser.getUserName());
        approve.setType(3);
        approve.setApprovalName(approvalName);
        approve.setTableList(JSONArray.toJSONString(list));
        approve.setFootList(dto.getFootList());
        saveOrUpdate(approve);

        dknTrialItemService.saveOrUpdateBatch(logs);
        dbApprovalLogService.approvalSubmit(orderNum,approvalName,dto);

        return respond;
    }

    @Override
    public void ywPostagePass(YwApprovaPassDto dto) {
        YwApprove ywApprove = findByApproveNo(dto.getApproveNo());
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        dbApprovalLogService.approvalPass(dto,"配送费审批");
    }

    @Override
    public void ywPostageCancel(String approveNo) {
        YwApprove ywApprove = findByApproveNo(approveNo);
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        LambdaQueryWrapper<DknTrialItem> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DknTrialItem::getApproveNo,approveNo);
        dknTrialItemService.remove(lambdaQueryWrapper);
        dbApprovalLogService.approvalCancel(approveNo,"配送费审批");
    }


    @Override
    public void ywPostageBack(YwApprovaPassDto dto) {
        YwApprove ywApprove = findByApproveNo(dto.getApproveNo());
        if(UtilValidate.isEmpty(ywApprove)){
            throw new YmException("参数有误！");
        }
        dbApprovalLogService.approvalBack(dto,"配送费审批");
    }
}
